package cb.com.etcdemo;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cb.com.etcdemo.API.API;
import cb.com.etcdemo.adapter.SimpleFragmentPagerAdapter;
import cb.com.etcdemo.bean.DeviceStateOnLine;
import cb.com.etcdemo.http.Okhttp;
import cb.com.etcdemo.view.BadgeView;
import cb.com.etcdemohgz.R;

/**
 * 资源界面
 * Created by cuibin on 2018/4/4.
 */

public class ResourceActivity extends BaseActivity {
    @BindView(R.id.tv_resource_insertAddress)
    TextView tvResourceInsertAddress;
    @BindView(R.id.tab_layout)
    TabLayout mTabLayout;
    @BindView(R.id.view_pager)
    ViewPager mViewPager;
    @BindView(R.id.button)
    Button button;
    private List<String> mPageTitleList = new ArrayList<String>();
    private List<Fragment> mFragmentList = new ArrayList<Fragment>();
    public static List<Integer> mBadgeCountList = new ArrayList<Integer>();
    private List<BadgeView> mBadgeViews;

    public static SimpleFragmentPagerAdapter mPagerAdapter;
    public static Handler mHandler;

    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 200) {
                setUpTabBadge();
            }
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_resource);
        ButterKnife.bind(this);
        mHandler = new MyHandler();
        initFragments();
        initView();
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(ResourceActivity.this, DevicesActivity.class));
            }
        });

    }

    private void initFragments() {
        // 初始化标题
        mPageTitleList.add("在线");
        mPageTitleList.add("离线");
        mPageTitleList.add("从未上线");
        // 初始化标题右上角的数字
        mBadgeCountList.add(0);
        mBadgeCountList.add(0);
        mBadgeCountList.add(0);

        // 初始化对应的fragment
        mFragmentList.add(OnLineFragment.getInstance(mPageTitleList.get(0)));
        mFragmentList.add(OfflineFragment.getInstance(mPageTitleList.get(1)));
        mFragmentList.add(NotOnLineFragment.getInstance(mPageTitleList.get(2)));
    }

    private void initView() {

        mPagerAdapter = new SimpleFragmentPagerAdapter(this, getSupportFragmentManager(),
                mFragmentList, mPageTitleList, mBadgeCountList);
        mViewPager.setAdapter(mPagerAdapter);
        mTabLayout.setupWithViewPager(mViewPager);
        // 关闭预加载，默认一次只加载一个Fragment
//        mViewPager.setOffscreenPageLimit(0);
        mViewPager.setCurrentItem(1);
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                mFragmentList.get(arg0).setUserVisibleHint(true);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });
        initBadgeViews();
//        setUpTabBadge();
    }

    /**
     * 初始化标题右上角标记
     */
    private void initBadgeViews() {
        if (mBadgeViews == null) {
            mBadgeViews = new ArrayList<>();
            for (int i = 0; i < mFragmentList.size(); i++) {
                BadgeView tmp = new BadgeView(this);
                tmp.setBadgeMargin(0, 6, 10, 0);
                tmp.setTextSize(10);
                mBadgeViews.add(tmp);
            }
        }
    }

    /**
     * 设置Tablayout上的标题的角标
     */
    private void setUpTabBadge() {
        // 1. 最简单
//        for (int i = 0; i < mFragmentList.size(); i++) {
//            mBadgeViews.get(i).setTargetView(((ViewGroup) mTabLayout.getChildAt(0)).getChildAt(i));
//            mBadgeViews.get(i).setText(formatBadgeNumber(mBadgeCountList.get(i)));
//        }

        // 2. 最实用
        for (int i = 0; i < mFragmentList.size(); i++) {
            TabLayout.Tab tab = mTabLayout.getTabAt(i);

            // 更新Badge前,先remove原来的customView,否则Badge无法更新
            View customView = tab.getCustomView();
            if (customView != null) {
                ViewParent parent = customView.getParent();
                if (parent != null) {
                    ((ViewGroup) parent).removeView(customView);
                }
            }

            // 更新CustomView
            tab.setCustomView(mPagerAdapter.getTabItemView(i));
        }

        // 需加上以下代码,不然会出现更新Tab角标后,选中的Tab字体颜色不是选中状态的颜色
        mTabLayout.getTabAt(mTabLayout.getSelectedTabPosition()).getCustomView().setSelected(true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mViewPager.setCurrentItem(1);
        mFragmentList.get(1).setUserVisibleHint(true);
//        findApiResourceAccountStationByPage();
    }

    private void findApiResourceAccountStationByPage() {
        try {
            Okhttp.get(API.Base + " /web/deviceState/listDeviceStateOnLineByPage?type=2&queryCriteria=", null, new Okhttp.Objectcallback() {
                @Override
                public void onsuccess(String st) {
                    try {
                        // 把JSON转换为PageUtils对象
                        DeviceStateOnLine page = JSON.parseObject(st,
                                DeviceStateOnLine.class);
                        mBadgeCountList.clear();
                        mBadgeCountList.add(page.getOnLineCount());
                        mBadgeCountList.add(page.getOffLineCount());
                        mBadgeCountList.add(page.getNotOnLine());
                        initView();
                    } catch (Exception e) {
                        // TODO: handle exception
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFalia(int code, String errst) {
//                    Toast.makeText(getActivity(), "网络错误，请检查网络！" + errst, Toast.LENGTH_SHORT).show();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
//    @Override
//    public void onClick(View v) {
//        mBadgeCountList.set(1, count++);
//        setUpTabBadge();
//    }
}
